package com.viknix.threadpool.manager.config.dump.processor;

import com.viknix.threadpool.manager.common.util.GroupKeyUtil;
import com.viknix.threadpool.manager.config.dump.ConfigInfo;
import com.viknix.threadpool.manager.config.dump.DumpConfigHandler;
import com.viknix.threadpool.manager.config.dump.DumpService;
import com.viknix.threadpool.manager.config.dump.task.DumpTask;
import com.viknix.threadpool.manager.config.event.ConfigDumpEvent;
import com.viknix.threadpool.manager.config.service.ConfigService;
import com.viknix.threadpool.manager.server.dependence.task.TpmTask;

import java.util.Objects;

/**
 * @Author: Dongqi
 * @Date: 2021/11/20 16:17
 * @Version 1.0
 * @Description: 转储处理器
 */
public class DumpProcessor implements TpmTaskProcessor {

    final DumpService dumpService;

    public DumpProcessor(DumpService dumpService) {
        this.dumpService = dumpService;
    }

    @Override
    public boolean process(TpmTask task) {
        ConfigService configService = dumpService.getConfigService();
        DumpTask dumpTask = (DumpTask) task;
        String[] pair = GroupKeyUtil.parseKey(dumpTask.getGroupKey());
        String dataId = pair[0];
        String group = pair[1];
        String tenant = pair[2];
        long lastModified = dumpTask.getLastModified();
        String handleIp = dumpTask.getHandleIp();
        boolean isBeta = dumpTask.isBeta();
        String tag = dumpTask.getTag();

        ConfigDumpEvent.ConfigDumpEventBuilder build = ConfigDumpEvent.builder().namespaceId(tenant).dataId(dataId)
                .group(group).isBeta(isBeta).tag(tag).lastModifiedTs(lastModified).handleIp(handleIp);

        ConfigInfo configInfo = configService.getConfigInfo(dataId, group, tenant);

        // 如果 configInfo 配置为null，说明需要将该配置从内存当中移除
        build.remove(Objects.isNull(configInfo));
        build.content(Objects.isNull(configInfo) ? null : configInfo.getContent());
        // 如果执行失败，该任务会被重新提交
        return DumpConfigHandler.configDump(build.build());
    }
}
